﻿using DimensionsHelper.Common.Contracts.Excel;

namespace DimensionsHelper.Client.WinUi.Helpers;

public record BorderLineInfo(BorderStyle Style, string Label, DoubleCollection DashArray, double Thickness);

public static class BorderHelper
{
    public static readonly float[] Normal = [];
    public static readonly float[] DotDashArray = [1, 1];
    public static readonly float[] DashedDashArray = [2, 2];
    public static readonly float[] DashDotDashArray = [2, 1, 1, 1];
    public static readonly float[] DashDotDotDashArray = [3, 1, 1, 1, 1, 1];


    static BorderHelper()
    {
        List<BorderLineInfo> infos = [];
        Type styleType = typeof(BorderStyle);
        FieldInfo[] fields = styleType.GetFields();

        foreach (FieldInfo field in fields)
        {
            if (!field.IsStatic || !field.IsLiteral)
            {
                continue;
            }

            object? fieldValue = field.GetValue(null);

            // 跳过0
            if (fieldValue is not BorderStyle obj || obj == BorderStyle.None)
            {
                continue;
            }

            string label = string.Empty;

            // DescriptionAttribute
            DescriptionAttribute? descAttr = field.GetCustomAttribute<DescriptionAttribute>();
            if (descAttr != null)
            {
                label = descAttr.Description;
            }

            infos.Add(new BorderLineInfo(obj, label, GetDashDoubleCollection(obj), GetThickness(obj, 1, 2, 3, 4)));
        }

        LineStyles = infos;
    }


    public static IReadOnlyList<BorderLineInfo> LineStyles
    {
        get;
    }


    public static float[] GetDashArray(BorderStyle style)
    {
        return style switch
        {
            BorderStyle.Dotted => DotDashArray,
            BorderStyle.DashDot or BorderStyle.MediumDashDot => DashDotDashArray,
            BorderStyle.DashDotDot or BorderStyle.MediumDashDotDot => DashDotDotDashArray,
            BorderStyle.Dashed or BorderStyle.MediumDashed => DashedDashArray,
            // 实线
            _ => Normal
        };
    }


    public static DoubleCollection GetDashDoubleCollection(BorderStyle style)
    {
        float[] array = GetDashArray(style);
        DoubleCollection collection = [.. array];
        return collection;
    }


    public static double GetThickness(BorderStyle style, double hair, double thin, double medium, double thick)
    {
        return style switch
        {
            BorderStyle.Hair => hair,
            BorderStyle.Medium or BorderStyle.MediumDashed or BorderStyle.MediumDashDot
                or BorderStyle.MediumDashDotDot => medium,
            BorderStyle.Thick => thick,
            BorderStyle.None => 0,
            _ => thin
        };
    }
}